package com.watchthelan.service.schedule.job;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.watchthelan.domain.Server;
import com.watchthelan.service.schedule.event.EventManager;
import com.watchthelan.service.server.ServerManager;

public class SimpleJob extends QuartzJobBean implements StatefulJob {
	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	
	private static final String APPLICATION_CONTEXT_KEY = "applicationContext";
	
	private ServerManager serverManager;

	
	@Override
	protected void executeInternal(JobExecutionContext ctx)
	throws JobExecutionException {
		logger.info("executing job");
		// TODO: start different jobs for each event
		try {
			ApplicationContext appCtx = getApplicationContext(ctx);
			serverManager = (ServerManager) appCtx.getBean("serverManager");
			logger.info("got server manager");
			Long serverId = (Long) ctx.getJobDetail().getJobDataMap().getLong("server_id");
			Server server = null;
			if (serverId != null) {
				server = serverManager.getServerById(serverId);
				int initialStatus = server.getStatus();
				int currentStatus = server.getRealStatus();
				if (initialStatus != currentStatus) {
					server.setStatus(currentStatus);
					logger.info("updatin server: " + server);
					serverManager.updateServer(server);
				}
			}
		} catch (Exception e) {
			logger.info("cauth exception: " + e.getMessage());
		}
	}
	
	private ApplicationContext getApplicationContext(JobExecutionContext context)
    throws Exception {
        ApplicationContext appCtx = null;
        appCtx = (ApplicationContext)context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
        if (appCtx == null) {
            throw new JobExecutionException(
                    "No application context available in scheduler context for key \"" + APPLICATION_CONTEXT_KEY + "\"");
        }
        return appCtx;
    }
}
